package com.icode.gulimall.cart.interceptor;

import com.icode.common.constant.CartConstant;
import com.icode.common.vo.MemberResponseVo;
import com.icode.gulimall.cart.to.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

import static com.icode.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2021-01-09 18:12
 */
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> loginUser = new ThreadLocal<>();

    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberResponseVo responseVo = (MemberResponseVo) session.getAttribute(LOGIN_USER);
        if (responseVo != null) {
            //用户登录状态
            userInfoTo.setUserId(responseVo.getId());
        }
        //查询是否存在"user-key"的cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //user-key
                String name = cookie.getName();
                if (CartConstant.TEMP_USER_COOKIE_NAME.equals(name)) {
                    //存在user-key
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setHasUserCookie(true);
                    userInfoTo.setIsTempUser(true);
                    loginUser.set(userInfoTo);
                    return true;
                }
            }
        }
        //如果没有"user-key"就分配一个
        String string = UUID.randomUUID().toString();
        userInfoTo.setUserKey(string);
        loginUser.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = loginUser.get();
        if (!userInfoTo.getHasUserCookie()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
